<?php
/**
 * @Author: CaiHongxuan
 * @Date:   2016-03-18 00:15:13
 * @Last Modified by:   CaiHongxuan
 * @Last Modified time: 2016-03-22 10:49:14
 */
class MenuModel extends Model{
	/**
	 * 创建自定义菜单
	 * @return [type] [description]
	 */
	public function createMenu($appid, $secret, $button, $matchrule = NULL){
		$url          = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
		$output       = $this->https_request($url);
		$jsoninfo     = json_decode($output, true);
		// 获取access_token凭证
		$access_token = $jsoninfo['access_token'];

		// foreach ($button as $item) {
		// 	foreach ($item as $k => $v) {
		// 		if(is_array($v)){
		// 			foreach ($item[$k] as $subitem) {
		// 				foreach ($subitem as $k2 => $v2) {
		// 					$subitem[$k2] = urlencode($v2);
		// 				}
		// 			}
		// 		}else{
		// 			$item[$k] = urlencode($v);
		// 		}
		// 	}
		// }

		// if(isset($matchrule) && !is_null($matchrule)){
		// 	foreach ($matchrule as $k => $v) {
		// 		$matchrule[$k] = urlencode($v);
		// 	}
		// 	$data = urldecode(json_encode(array('button' => $button, 'matchrule' => $matchrule)));
		// 	$url  = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $access_token;
		// }else{
		// 	$data = urldecode(json_encode(array('button' => $button)));
			$url  = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $access_token;
		// }
		$res = $this->https_request($url, $data);
		return json_decode($res, true);
	}

	/**
	 * 当$data为null时获取access_token凭证；当$data不为null时，创建自定义菜单
	 * @param  [type] $url  [description]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public function https_request($url,$data = null){
	    $curl = curl_init();
	    curl_setopt($curl, CURLOPT_URL, $url);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	    if (!empty($data)){
	        curl_setopt($curl, CURLOPT_POST, 1);
	        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	    }
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	    $output = curl_exec($curl);
	    curl_close($curl);
	    return $output;
	}

}
